import React, { Component, Suspense } from 'react';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import moment from 'moment';
import { connect } from 'dva';
import PageLoading from '@/components/PageLoading';
import dataTime from '../../../utils/dataTime';
import { FormattedMessage } from 'umi-plugin-react/locale';
import download from '@/utils/download';
import ContextModal from '@/utils/contextModal';
import { doChatRecords } from '@/services/datastatistics';
const EditingKnowledge = React.lazy(() => import('@/pages/KnowledgeManagement/Overview/EditingKnowledge/editingKnowledge'));
import UpDownCharacter from '../../../modules/UpDownCharacter';
import { Row, Col, Card, Icon, Table, Form, Spin, Modal, Button, message, Tabs, DatePicker, Select, Input, Tooltip, Drawer, Pagination } from 'antd';
import styles from './index.less';
import EditQa from '../../KnowledgeManagement/Overview/editQa';
import tableDataCheck from '@/utils/isBackPrevPage';
import RelatedKnowledgeV2 from '@/utils/RelatedKnowledgeV2';
const TabPane = Tabs.TabPane;
const FormItem = Form.Item;
const { RangePicker } = DatePicker;
const dateFormat = 'YYYY/MM/DD';
const Option = Select.Option;
const Search = Input.Search;
const MyIcon = Icon.createFromIconfontCN({
  scriptUrl: '//at.alicdn.com/t/font_1131883_8lpmy5tq6hn.js', // 在 iconfont.cn 上生成
});
@connect(({ process, loading }) => ({
  process,
  loading: loading.effects['waitingLearningIssue/fetch'],
}))
class UnknownProblem extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loginjqr: false,
      logins: true,
      qaListTable: [],
      total2: '',
      knowledgeList: [],
      upDownDate: [],
      total: '',
      beginTime: '',
      overTime: '',
      total: '',
      login: false,
      dataSource: [],
      pageSize: 15,
      page: 1,
      selectedRowKeys: [],
      electa: 'time',
      electb: 'false',
      portJudge: true,
      break: false,
      field: '1',
      question: '',
      evaluate: '',
      ignored: false,
      order: 'time',
      asc: 'desc',
      shutRelevance: false,
      showModel1: false,
      numberRadio: '1',
      pageSizetwo: 10,
      pagetwo: 1,
      nodeId: '',
      nodeIdName: '所有分类',
      close: false,
      qaId: '',
      isUpdate: false,
      aALeng: '',
      glLeng: 10,
      qustzhuye: '',
      sort: '',
      unknownId: '',
      unresolvedId: '',
      relatedVisible: false,
      currentQaId: '',
      currentQuestion: '',
      contextModalVisible: false,
      contextMessage: [],
      isDownloading: false,
    };
  }

  componentWillMount() {
    let sysTime = dataTime.formatDate(new Date().getTime()); // 初始时间
    let toTime = moment().subtract('days', 7).format('YYYY/MM/DD');
    this.setState({
      beginTime: toTime.replace(/\//g, '-'),
      overTime: sysTime.replace(/\//g, '-'),
    });
  }

  // eslint-disable-next-line react/sort-comp
  fetch = (query, ignored, from, to, page, limit, order, sort) => {
    if (from && to) {
      this.setState({ login: true });
      const { dispatch, currentUser } = this.props;
      this.reqRef = requestAnimationFrame(() => {
        dispatch({
          type: 'waitingLearningIssue/fetch',
          payload: { query, ignored, from, to, current: this.state.page, size: limit, order, sort },
          callback: res => {
            let temp = res.records;
            temp.map((item, index) => (item['key'] = index));
            this.props.totala(Number(res.total));
            this.setState({ dataSource: temp, selectedRowKeys: [], total: Number(res.total), selectedRows: null, login: false, logins: true, });
          },
        });
      });
    } else {
      message.error(`请选择开始至结束日期`);
    }
  };

  componentDidMount() {
    const { seek, beginTime, overTime, page, pageSize, order, asc } = this.state;
    this.fetch(seek, this.state.break, beginTime, overTime, page, pageSize, order, asc);
  }


  // 日期选择｛开始日期——结束日期｝
  onChange = (date, dateString) => {
    this.setState({
      beginTime: dateString[0].replace(/\//g, '-'),
      overTime: dateString[1].replace(/\//g, '-'),
    });
  };

  // 查看
  handleSubmit = () => {
    let userInfo = this.props.form.getFieldsValue(); // 获取数据
    // let usercz = this.props.form.resetFields();// 重置表单数据
    this.props.form.validateFields((err, values) => {
      if (!err) {
        this.setState({ seek: userInfo.seek });
        let a = '';
        if (userInfo.lose === 'true') {
          a = true;
          this.setState({ electb: 'true', portJudge: false, break: true, page: 1 }, () => {
            const { seek, beginTime, overTime, page, pageSize, order, asc } = this.state;
            this.fetch(seek, true, beginTime, overTime, page, pageSize, order, asc);
          });
        } else if (userInfo.lose === 'false') {
          a = false;
          this.setState({ electb: 'false', portJudge: true, break: false, page: 1 }, () => {
            const { seek, beginTime, overTime, page, pageSize, order, asc } = this.state;
            this.fetch(seek, false, beginTime, overTime, page, pageSize, order, asc);
          });
        }
      }
    });
  };

  newlyAdded = row => {
    this.EditingKnowledge.showEditDrawer(null, row.question, null, '', '', '', 0);
  };

  onClose = (type) => {
    this.setState({ close: false }, () => {
      const { seek, beginTime, overTime, page, pageSize, order, asc, dataSource } = this.state;
      if (type && type === 'done' && !this.state.break) {
        const newCurrent = tableDataCheck(dataSource, page);
        this.setState({ page: newCurrent }, () => {
          this.fetch(seek, this.state.break, beginTime, overTime, newCurrent, pageSize, order, asc);
        })
      } else {
        this.fetch(seek, this.state.break, beginTime, overTime, page, pageSize, order, asc);
      }
    });
  };

  ignore = row => {
    let its = [];
    its.push(row.question);
    const { dispatch } = this.props;
    const { seek, beginTime, overTime, page, pageSize, order, asc, dataSource } = this.state;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'waitingLearningIssue/fetchc',
        payload: { questions: its, ignored: this.state.portJudge },
        callback: res => {
          message['success'](`${res.msg}`);
          //判断是否需要加载上一页数据 2022.4.8
          const newCurrent = tableDataCheck(dataSource, page, its);
          this.setState({ page: newCurrent }, () => {
            this.fetch(seek, this.state.break, beginTime, overTime, newCurrent, pageSize, order, asc);
          })
        },
      });
    });
  };

  recovery = row => {
    let its = [];
    its.push(row.question);
    const { seek, beginTime, overTime, page, pageSize, order, asc, dataSource } = this.state;
    const { dispatch } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'waitingLearningIssue/fetchc',
        payload: { questions: its, ignored: this.state.portJudge },
        callback: res => {
          message['success'](`${res.msg}`);
          //判断是否需要加载上一页数据 2022.4.8
          const newCurrent = tableDataCheck(dataSource, page, its);
          this.setState({ page: newCurrent }, () => {
            this.fetch(seek, this.state.break, beginTime, overTime, newCurrent, pageSize, order, asc);
          })
        },
      });
    });
  };

  down = () => {
    const { dispatch } = this.props;
    this.state.isDownloading = true;
    const { seek, beginTime, overTime, page, pageSize, order, asc } = this.state;
    let userInfo = this.props.form.getFieldsValue(); // 获取数据
    const data = { from: beginTime, ignored: userInfo.lose, order: order, sort: asc, to: overTime, query: userInfo.seek, type: '1', };
    dispatch({
      type: 'waitingLearningIssue/exportWz',
      payload: data,
      callback: res => {
        setTimeout(() => {
          this.setState({ isDownloading: false });
        }, 500);
        download.byBlob(res.data.blob, res.data.fileName);
      },
    });
  };

  downloading = () => {
    this.setState({ isDownloading: true }, () => this.down());
  };

  /**
   * 打开关联问
   */
  openRelatedModal = (question, id) => {
    this.setState({ relatedVisible: true, currentQuestion: question, currentQaId: id, }, () => {
      this.RelatedKnowledge.openAndInit([])
    });
  };

  /**
   * 关闭关联问modal
   */
  closeRelatedModal = (type) => {
    const { seek, beginTime, overTime, page, pageSize, order, asc, dataSource } = this.state;
    //判断是否需要加载上一页数据 2022.4.8
    const newCurrent = tableDataCheck(dataSource, page);
    this.setState({ page: newCurrent }, () => {
      this.fetch(seek, this.state.break, beginTime, overTime, newCurrent, pageSize, order, asc);
    })
  };

  /**
   * 获取上下文
   * @returns {*}
   */
  getChatRecords = async row => {
    if (row.count > 1) {
      const { beginTime, overTime } = this.state;
      const obj = { question: row.question, from: beginTime, to: overTime, type: 1 };
      this.props.openSessionRecordModal(obj, row)
    } else {
      let res = await doChatRecords({
        sessionId: row.lastChatId,
        time: moment(row.createTime).format('YYYY-MM-DD HH:mm:ss'),
      });
      this.setState({ contextMessage: res, contextModalVisible: true, });
    }
  };

  /**
   * 关闭上下文
   * @returns {*}
   */
  cancelContextModal = () => {
    this.setState({ contextModalVisible: false, contextMessage: [], });
  };

  render() {
    const { getFieldDecorator } = this.props.form;

    return (
      <Suspense fallback={<PageLoading />}>
        <div style={{ padding: '0px 20px 0px 30px' }}>
          <div style={{ marginBottom: 20 }} className={styles.fromColumn}>
            <div>
              <Form className={styles.buttonA} layout="inline">
                <FormItem>
                  <RangePicker
                    onChange={this.onChange}
                    style={{ width: 220 }}
                    defaultValue={[
                      moment(this.state.beginTime, dateFormat),
                      moment(this.state.overTime, dateFormat),
                    ]}
                    format={dateFormat}
                  />
                </FormItem>
                <FormItem>
                  {getFieldDecorator('lose', { initialValue: this.state.electb, })(
                    <Select style={{ width: 130 }}>
                      <Option value="false">未忽略</Option>
                      <Option value="true">已忽略</Option>
                    </Select>
                  )}
                </FormItem>
                <FormItem>
                  {getFieldDecorator('seek', { initialValue: '', })(
                    <Input onPressEnter={this.handleSubmit} placeholder="请输入搜索问题" />
                  )}
                </FormItem>
                <FormItem className="buttonYs">
                  <Button onClick={this.handleSubmit} type="primary">查询</Button>
                </FormItem>
                <FormItem className="buttonYs">
                </FormItem>
              </Form>
            </div>
            <span style={{ display: 'flex', gap: 20, alignItems: 'center' }}>
              <span className="buttonYs">
                <Button onClick={this.downloading} loading={this.state.isDownloading}>导出</Button>
              </span>
              {this.state.electb === 'false' ? (
                <span className="zdyButtonA">
                  <Button onClick={this.handleRelete} type="primary" icon="eye-invisible">批量忽略</Button>
                </span>
              ) : (
                <span className="zdyButtonA">
                  <Button onClick={this.handleRelete} type="primary" icon="eye-invisible">批量恢复</Button>
                </span>
              )}
            </span>
          </div>
          {this.lessdata()}
          <Drawer
            title={<FormattedMessage id="app.overView.editQa" />}
            placement="right"
            closable
            onClose={this.onClose}
            visible={this.state.close}
            width={800}
            destroyOnClose
          >
            <EditQa unknownId={this.state.unknownId} questions={this.state.qaId} onClose={this.onClose} />
          </Drawer>
          <RelatedKnowledgeV2
            onRef={ref => this.RelatedKnowledge = ref}
            applicationId={''}
            chooseType='radio'
            qaId={this.state.currentQaId}
            question={this.state.currentQuestion}
            refreshList={this.closeRelatedModal}
          />
          <ContextModal visible={this.state.contextModalVisible} message={this.state.contextMessage} cancelContextModal={this.cancelContextModal} />
          <EditingKnowledge onRef={ref => (this.EditingKnowledge = ref)} refreshList={this.onClose} ifCapacity={true} />
        </div>
      </Suspense>
    );
  }

  handleChange = (pagination, filters, sorter) => {
    if (sorter.columnKey === 'count') {
      if (sorter.order === 'ascend') {
        // 升序
        this.setState({ order: 'count', asc: 'asc' });
        this.fetch(this.state.seek, this.state.break, this.state.beginTime, this.state.overTime, this.state.page, this.state.pageSize, 'count', 'asc');
      };
      if (sorter.order === 'descend') {
        // 降序
        this.setState({ order: 'count', asc: 'desc' });
        this.fetch(this.state.seek, this.state.break, this.state.beginTime, this.state.overTime, this.state.page, this.state.pageSize, 'count', 'desc');
      };
      this.setState({ sortOrder: sorter.order, evaluate: 'count', });
    };
    if (sorter.columnKey === 'createTime') {
      if (sorter.order === 'ascend') {
        // 升序
        this.setState({ order: 'time', asc: 'asc' });
        this.fetch(this.state.seek, this.state.break, this.state.beginTime, this.state.overTime, this.state.page, this.state.pageSize, 'time', 'asc');
      };
      if (sorter.order === 'descend') {
        // 降序
        this.setState({ order: 'time', asc: 'desc' });
        this.fetch(this.state.seek, this.state.break, this.state.beginTime, this.state.overTime, this.state.page, this.state.pageSize, 'time', 'desc');
      };
      this.setState({ sortOrder: sorter.order, evaluate: 'count', });
    }
  };

  lessdata = () => {
    const { selectedRowKeys } = this.state;
    // 多选
    const rowCheckSelection = {
      type: 'checkbox',
      selectedRowKeys, //告诉插件我们点击的哪一行
      onChange: (selectedRowKeys, selectedRows) => {
        this.setState({ selectedRowKeys, selectedRows: selectedRows, });
      },
    };
    const columns = [
      {
        title: `未知问题`,
        width: 'calc(20vw)',
        dataIndex: 'question',
        render(item) {
          return (
            // <div className={styles.wtbj}>{item}</div>
            <div className={styles.wtbj} dangerouslySetInnerHTML={{ __html: item }}></div>
          );
        },
      },
      {
        title: '询问次数',
        width: 160,
        align: 'center',
        dataIndex: 'count',
        sorter: (a, b) => { },
        // sortOrder:this.state.sortOrder
      },
      {
        title: '最近询问时间',
        width: 240,
        align: 'center',
        dataIndex: 'createTime',
        sorter: (a, b) => { },
        // sorter: (a, b) => a.createTime - b.createTime,
        render: createTime => {
          return moment(createTime).format('YYYY-MM-DD HH:mm:ss');
        },
      },
      {
        title: '操作',
        width: 320,
        align: 'center',
        render: (text, row) => {
          return (
            <div className={styles.wt}>
              <Button type="primary" icon="link" size="small" onClick={() => this.openRelatedModal(row.question, row.id)}>关联</Button>
              <Button type="primary" size="small" icon="plus" onClick={() => this.newlyAdded(row)}>新增</Button>
              {this.state.electb === 'false' ? (
                <Button type="primary" icon="eye-invisible" size="small" onClick={() => this.ignore(row)}>忽略</Button>
              ) : (
                <Button type="primary" size="small" onClick={() => this.recovery(row)}> <MyIcon type="icon-huifu" />恢复</Button>
              )}
              <Button type={'primary'} size="small" onClick={() => this.getChatRecords(row)}>会话记录</Button>
            </div>
          );
        },
      },
    ];

    return (
      <Spin spinning={this.state.login}>
        <Table
          className="zdyTable"
          rowSelection={rowCheckSelection}
          style={{ padding: '0px 0px 0px 0px' }}
          columns={columns}
          dataSource={this.state.dataSource} //数据
          onChange={this.handleChange}
          scroll={{ y: 587 }}
          pagination={false}
        />
        {Number(this.state.total) > 10 ? (
          <Pagination
            style={{ textAlign: 'right', marginTop: 16 }}
            total={Number(this.state.total)}
            pageSize={this.state.pageSize}
            current={this.state.page}
            // pageSizeOptions={['15', '30', '50', '100']}
            // showSizeChanger={true}
            showQuickJumper={true}
            onChange={this.onChangeA}
            // onShowSizeChange={this.onShowSizeChangeA}
          />
        ) : null}
      </Spin>
    );
  };

  onChangeA = val => {
    // 页数选择
    this.setState({ page: val }, () => {
      setTimeout(() => {
        const { seek, beginTime, overTime, page, pageSize, order, asc } = this.state;
        this.fetch(seek, this.state.break, beginTime, overTime, page, pageSize, order, asc);
      }, 1);
    });
  };

  // 每页显示多少条数据
  onShowSizeChangeA = (current, pageSize) => {
    this.setState({ pageSize: pageSize, page: current }, () => {
      const { seek, beginTime, overTime, pageSize, page, order, asc } = this.state;
      this.fetch(seek, this.state.break, beginTime, overTime, page, pageSize, order, asc);
    });
  };

  handleRelete = () => {
    let rows = this.state.selectedRows;
    if (this.state.break === false) {
      // 忽略
      if (rows) {
        let its = [];
        rows.map(item => {
          its.push(item.question);
        });
        Modal['confirm']({
          title: '忽略问题',
          content: '确定忽略吗？',
          okText: '确认',
          cancelText: '取消',
          onOk: () => {
            const { dispatch } = this.props;
            const { seek, beginTime, overTime, page, pageSize, order, asc, dataSource } = this.state;
            this.reqRef = requestAnimationFrame(() => {
              dispatch({
                type: 'waitingLearningIssue/fetchc',
                payload: { questions: its, ignored: this.state.portJudge },
                callback: res => {
                  message['success'](`${res.msg}`);
                  //判断是否需要加载上一页数据 2022.4.8
                  const newCurrent = tableDataCheck(dataSource, page, its)
                  this.setState({ page: newCurrent }, () => {
                    this.fetch(seek, this.state.break, beginTime, overTime, newCurrent, pageSize, order, asc);
                  })
                },
              });
            });
          },
          onCancel() { },
        });
      } else {
        message['error']('您还没有选择！');
      }
    } else if (this.state.break === true) {
      if (rows) {
        let its = [];
        rows.map(item => {
          its.push(item.question);
        });
        const { dispatch } = this.props;
        const { seek, beginTime, overTime, page, pageSize, order, asc, dataSource } = this.state;
        this.reqRef = requestAnimationFrame(() => {
          dispatch({
            type: 'waitingLearningIssue/fetchc',
            payload: { questions: its, ignored: this.state.portJudge },
            callback: res => {
              message['success'](`${res.msg}`);
              //判断是否需要加载上一页数据 2022.4.8
              const newCurrent = tableDataCheck(dataSource, page, its)
              this.setState({ page: newCurrent }, () => {
                this.fetch(seek, this.state.break, beginTime, overTime, newCurrent, pageSize, order, asc);
              })
            },
          });
        });
      } else {
        message['error']('您还没有选择！');
      }
    }
  };

}
export default connect(({ user }) => ({
  // 全局数据 portJudge
  currentUser: user.currentUser,
}))(Form.create()(UnknownProblem));
